package com.jack.concurrency;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * Created by zhang_j on 2019/12/5
 */
public class MyCyclicBarrier {
    private static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(100,120,60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadFactoryBuilder().setNameFormat("mycyclicbarrier-pool-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(4);
        for(int i=0;i<4;i++){
            EXECUTOR_SERVICE.execute(()->{
                System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
                try {
                    Thread.sleep(5000);      //以睡眠来模拟写入数据操作
                    System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕，等待其他线程写入完毕");
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }catch(BrokenBarrierException e){
                    e.printStackTrace();
                }
                System.out.println("所有线程写入完毕，继续处理其他任务...");
            });
        }
    }
}
